package org.grow.cooldown.ScoreModule;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.grow.cooldown.ScoreModule.entity.Score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
@RequestMapping("/score/")
@RestController
public class ScoreCtrl {

    @Autowired
    MongoCollection<Document> scoreMongo;
    private Random random = new Random();
    @Autowired
    MongoTemplate mongoTemplate;

    @PostMapping("/mono/")
    public Score postScore(@RequestBody Score score) {
        score.setScoreId("s_" + random.nextInt(899) + 100);
        score.setScoreCT(LocalDate.now());
        score.valid();

        Score score1 = mongoTemplate.save(score);
        return score1;
    }

    @PutMapping("/mono/")
    public Score putScore(@RequestBody Score score) {
        if (StringUtils.isEmpty(score.getScoreId()))
            throw new Score.ScoreException("scoreId missed");
        score.valid();
        System.out.println(score.getScoreId());
        String robo3t = String.format("{_id:'%s'}", score.getScoreId());
        System.out.println(robo3t);
        Document m = scoreMongo.find(Document.parse(robo3t)).first();

        System.out.println(m);
        if (m == null || m.isEmpty()) throw new Score.ScoreException("this is new ");
        Score score1 = mongoTemplate.save(score);
        return score1;
    }

    @GetMapping("/flux/")
    public Map<String, Object> getScores() {
        String robo3t = String.format("{python:{$gt:%d}}", 50);
//        Document document = mongoTemplate.executeCommand(robo3t);

        FindIterable<Document> scores = scoreMongo
                .find(Document.parse(robo3t));
        return scores.first();
    }

    @GetMapping("/mono/{id}")
    public Map<String, Object> getScore(@PathVariable(value = "id") String id) {
        String auth = SessionAuthIntercepter.getAuth();
        System.out.println(auth);
        String r = String.format("{_id:'%s'}", id);
        FindIterable<Document> documents = scoreMongo.find(Document.parse(r));
        return documents.first();
    }
    @GetMapping("/mono/url/{id}")
    public Map<String,Object> testHoldUrl(@PathVariable String id){
        HolderIntercepter.setTitle(HolderIntercepter.getTitle()+" === >> controller change");
//        .set(l.get()+"  ===>controller change");
        System.out.println(HolderIntercepter.getTitle());
        return this.getScore(id);
    }

    @DeleteMapping("/mono/{id}")
    public Boolean deleteScore(@PathVariable(value = "id") String id) {
        String r = String.format("{_id:'%s'}", id);
        DeleteResult deleteResult = scoreMongo.deleteOne(Document.parse(r));
        return deleteResult.wasAcknowledged();
    }

    @GetMapping("/flux/sama")
    public List<Map<String, Object>> playsama() {
        String r = String.format("    {$group:{\n" +
                "        _id: '$%s',\n" +
                "        sumPython:{\n" +
                "            $sum: '$python'\n" +
                "            }\n" +
                "        }\n" +
                "    }", "operatorId");
        AggregateIterable<Document> documents = scoreMongo.aggregate(List.of(Document.parse(r)));
        LinkedList<Map<String, Object>> maps = new LinkedList<>();
        for (Document document : documents) {
            maps.add(document);

        }
        return maps;

    }


}
